package cn.jxau.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.plugins.Page;

import cn.jxau.bean.form.ModifyPwd;
import cn.jxau.bean.po.Article;
import cn.jxau.bean.po.User;
import cn.jxau.bean.po.UserCollectionsType;
import cn.jxau.bean.vo.Email;
import cn.jxau.bean.vo.JsonResult;
import cn.jxau.common.util.BaseFileRelativeUtil;
import cn.jxau.common.util.FileUpload;
import cn.jxau.common.util.IPTimeStamp;
import cn.jxau.common.util.JacksonUtils;
import cn.jxau.common.util.MailServer;
import cn.jxau.common.util.ProUtils;
import cn.jxau.common.util.WebTools;

/**
 * 和普通用户相关的操作
 * @author licho
 *
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
	
	private static final Logger log=Logger.getLogger(UserController.class);
	/**
	 * 根据传入的参数判断用户名或者邮箱是否存在
	 * @param userName
	 * @param email
	 * @return
	 */
	@RequestMapping("/exist")
	@ResponseBody
	public Map<String,Object> assertUserExist(@RequestParam(name="name",required=false)String userName,
			@RequestParam(name="email",required=false)String email){
		boolean flag=userService.userIsExist(userName, email);
		Map<String, Object> map=new HashMap<>();
		map.put("valid", flag ?false :true);
		return map;
	}
	
	@RequestMapping("/userList")
	@ResponseBody
	public JsonResult userList(Page<User> page){
		JsonResult result=null;
		List<User> list=userService.getUserListByPage(page);
		if(list!=null&&list.size()>0){
			result=renderSuccess("获取列表成功!");
			result.addData("lists", list);
		}else{
			result=renderError("学生列表为空或者发生服务器错误");
		}
		result.addData("page", page);
		return result;
	}
	
	@RequestMapping("/register")
	@ResponseBody
	public ModelAndView register(@Valid User user,BindingResult br){
// 		显示错误信息
//		System.out.println(br.getErrorCount());
//		for (ObjectError oe: br.getAllErrors()) {
//			System.out.println(oe.getDefaultMessage());
//		}
//		System.out.println(user);

		ModelAndView mv = new ModelAndView();
		if(br.getErrorCount()==0){
			boolean flag=userService.userIsExist(user.getName(), user.getEmail());
			if(!flag){
				if(userService.insertUser(user)){
					mv.setViewName("login");
				}
			}
		}else{
			mv.setViewName("register");
			mv.addObject("error", br.getAllErrors());
			mv.addObject("show", "show");
		}
		return mv;
	}
	
	
	/**
	 * 该处理方法用于上传富文本图片，并且返回该imge的服务器端的可访问地址。
	 * @param file
	 * @return
	 */
	@RequestMapping("/uploadImage")
	@ResponseBody
	public JsonResult uploadImage(HttpServletResponse response,MultipartFile file){
		response.setHeader("Access-Control-Allow-Origin", "*");//允许跨域，用作测试
		JsonResult result=null;
		String imgBaseURL="/pic/";
		try{
			FileUpload upload=WebTools.saveFileResultWithFileUpload(file);
			result=renderSuccess("上传图片成功");
			result.addData("url", imgBaseURL+upload.getFileName());//将图片的引用url进行写入。
		}catch (Exception e) {
			e.printStackTrace();
			result=renderError("未知错误");
		}
		return result;
	}
	
	/**
	 * 提交上传文章表单
	 */
	/**
	 * @param article
	 * @param file
	 * @param content
	 * @param request
	 * @return
	 */
	@RequestMapping("/uparticle")
	public ModelAndView uparticle(Article article,MultipartFile file,String content,HttpServletRequest request){
		ModelAndView mv = new ModelAndView();
		try{
			FileUpload upload=WebTools.saveFileResultWithFileUpload(file);
			article.setImageUrl(upload.getFileName());
			User user = (User) request.getSession().getAttribute("user");
			if(user!=null){
				article.setAuthorID(user.getId());
			}
			String filename = new IPTimeStamp().getIPTimeStampRand();
			article.setPath(filename);
			BaseFileRelativeUtil.overrideToFile(content, "E:/upload/text/"+filename+".txt", "utf-8");
			if(articleService.insertArticle(article)>0){
				mv.setViewName("articlemanager");
			}else{
				mv.addObject("msg", "文章上传失败");
				mv.setViewName("upaticle");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}
	
	/**
	 * 用来更新用户信息就，每次更新用户信息后记得更新session中User对象的最新状态
	 * @param user
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public JsonResult updateUserInfo(HttpSession session,User user){
		JsonResult result=null;
		System.out.println(user);
		boolean flag=userService.updateUserStatus(user);
		if(!flag){
			result=renderError("未知错误，更新失败!");
			return result;
		}
		result=renderSuccess("更新成功!");
		User newInfo=userService.getUserByid(user.getId());
		session.setAttribute("user", newInfo);
		session.setAttribute("juser",JacksonUtils.converToJson(newInfo));
		return result;
	}
	/**
	 * 
	 * @param file
	 * @param uid
	 * @return
	 */
	@RequestMapping("/saveavator")
	@ResponseBody
	public JsonResult setAvator(HttpSession session,@RequestParam("avator")MultipartFile file,@RequestParam("uid")Long uid){
		JsonResult result=null;
		String basePath=ProUtils.getProperty("file.save")+"/"+ProUtils.getProperty("avator.save");
		FileUpload upload=WebTools.saveFileResultWithFileUpload(file,basePath);
		String imgURL="/pic/avator/"+upload.getFileName();
		User user=new User();
		user.setAvator(imgURL);
		user.setId(uid);
		boolean flag=userService.updateUserStatus(user);
		if(!flag){
			result=renderError("未知错误，更新失败!");
			return result;
		}
		result=renderSuccess("更新成功!");
		result.addData("avator",imgURL);
		User newInfo=userService.getUserByid(user.getId());
		session.setAttribute("user", newInfo);
		session.setAttribute("juser",JacksonUtils.converToJson(newInfo));
		return result;
	}
	
	/**
	 * 获取邮箱验证码
	 * @param uid 要发送的用户id
	 * @return
	 */
	@RequestMapping("/authcode")
	@ResponseBody
	public JsonResult getAuthenticationCode(HttpSession session,Long uid){
		JsonResult result=null;
		User user=userService.getUserByid(uid);
		if(user==null)
		{
			result=renderError("非法闯入");
			return result;
		}
		Integer code=new Random().nextInt(10000);
		Email email=Email.getValidateEmali(user, code.toString());
		MailServer.sendEmail(email);
		result=renderSuccess("响应成功");
		result.addData("code", code);
		session.setAttribute("code", code);
		return result;
	}
	
	/**
	 * 修改用户密码
	 * @param info
	 * @return
	 */
	@RequestMapping("modifyPwd")
	@ResponseBody
	public JsonResult modifyPass(@Valid ModifyPwd info,BindingResult br,HttpSession session){
		JsonResult result=null;
		if(br.hasErrors()){
			//前台会做验证，如果后台验证出错，说明非法闯入，
			result=renderError("非法闯入");
		}
		Integer code=info.getCode();
		Integer rcode=(Integer)session.getAttribute("code");
		if(rcode!=null&&rcode.equals(code)){
			result=userService.modifyPwd(info);
			if(result.getStatus().equals("200"))
				session.invalidate();//失效session
		}else{
			result=renderError("验证码错误");
		}
		return result;
	}
	
	/**
	 * 通过ajax来判断用户是否登录，如果未登录，返回403,否则返回用户数据
	 * @param session
	 * @return
	 */
	@RequestMapping("assert")
	@ResponseBody
	public JsonResult assertLogin(HttpSession session){
		JsonResult result=renderSuccess("用户已登录");
		result.addData("user",session.getAttribute("user"));
		return result;
	}

}






































